singleApp.controller('listCtrl', ['$http', '$scope', '$sce', 'PageService', function ($http, $scope, $sce, PageService) {
    $scope.list = [];
    $scope.recipe_list = [];
    $scope.model_select_all = false;

    /*
     * init
     */
    $scope.init = function () {
        layer.load(2);

        var api_url = window.singleConfig.rootUrl + "api/admin/ListService/getAll?";

        $http.get(api_url).then(function (result) {
            var data = result.data.data;
            $scope.list = data;
            layer.closeAll();
        }, function () { });
    };

    $scope.init();

    $scope.model_newlist = { model: "", entry: null, name: "", tag: "" };
    $scope.showAddOrEditList = function (entry) {
        if (entry == null) {
            $scope.model_newlist = { model: "add", entry: null, name: "", tag: "" };
        }
        else {
            $scope.model_newlist = { model: "edit", entry: entry, name: entry.name, tag: entry.tag };
        }

        layer.open({
            type: 1,
            shade: false,
            title: entry == null ? "Add New List" : "Edit List: " + entry.name,
            content: $('#divAddOrEdirList'),
            area: ['530px', '320px'],
            cancel: function (index) {
                layer.closeAll();
            }
        });
    };

    /*
     * confirm add or edit
     */
    $scope.confirmAddOrEditList = function () {
        if ($scope.model_newlist.name == "") {
            layer.msg("Please input list's name !");
            return;
        }
        if ($scope.model_newlist.tag == "") {
            layer.msg("Please input list's tag !");
            return;
        }

        layer.load(2);

        var api_url = window.singleConfig.rootUrl + "api/admin/ListService/add";
        var postdata = { name: $scope.model_newlist.name, tag: $scope.model_newlist.tag };
        if ($scope.model_newlist.entry != null) {
            api_url = window.singleConfig.rootUrl + "api/admin/ListService/update";
            postdata = { id: $scope.model_newlist.entry.id, name: $scope.model_newlist.name, tag: $scope.model_newlist.tag };
        }
        
        $http({
            method: 'POST',
            url: api_url,
            data: $.param(postdata),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        })
		.then(function (result) {
		    var data = result.data;
		    if (data.code == "success") {
		        layer.closeAll();
		        $scope.init();
		    }
		    else {
		        layer.closeAll();
		        layer.msg(data.message);
		    }
		}, function (data) {
		    layer.closeAll();
		    layer.msg("Error to add new list.");
		});
    };

    /*
     * delete list
     */
    $scope.delete = function (item) {
        layer.confirm('Are you sure to delete this list ?', { icon: 3, title: 'Message', btn: ['Confirm', 'Cancel'] }, function (index) {
            layer.load(2);
            var api_url = window.singleConfig.rootUrl + "api/admin/ListService/delete?id=" + item.id;
            $http.get(api_url).then(function (result) {
                angular.forEach($scope.list, function (data, index, array) {
                    if (item.id == data.id) {
                        $scope.list.splice(index, 1);
                    }
                });
                layer.closeAll();
            }, function () { });
        });
    };

    /*
     * toggle status
     */
    $scope.toggleStatus = function (recipe) {
        layer.load(2);
        var parms = [
           "id=" + recipe.id,
           "status=" + (parseInt(recipe.status) == 0 ? 1 : 0)
        ];

        var api_url = window.singleConfig.rootUrl + "api/admin/RecipeService/updateStatus?" + parms.join("&");
        $http.get(api_url).then(function (data) {
            recipe.status = parseInt(recipe.status) == 0 ? 1 : 0;
            layer.closeAll();
        }, function () { });
    };

    $scope.model_choose_recipe = {};
    $scope.chooseRecipe = function (entry) {
        $scope.model_choose_recipe = entry;
        angular.forEach($scope.recipe_list, function (data, index, array) {
            if (entry.id_list.indexOf(data.id) != -1) {
                data.selected = true;
            }
            else {
                data.selected = false;
            }
        });

        layer.open({
            type: 1,
            shade: false,
            title: "Choose Recipe - " + entry.name,
            content: $('#divChooseRecipe'),
            area: ['830px', '620px'],
            cancel: function (index) {
                layer.closeAll();
            }
        });
    };

    $scope.confirmChooseRecipe = function () {
        var chooseid_list = [];
        angular.forEach($scope.recipe_list, function (data, index, array) {
            if (data.selected == true) {
                chooseid_list.push(data.id);
            }
        });
        if (chooseid_list.length == 0) {
            layer.msg("Please choose at least one recipe !");
            return;
        }
        //console.log(chooseid_list);
        $http({
            method: 'POST',
            url: window.singleConfig.rootUrl + "api/admin/ListService/chooseRecipe",
            data: $.param({ id: $scope.model_choose_recipe.id, id_list: chooseid_list.join(",") }),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        })
		.then(function (result) {
		    var data = result.data;
		    if (data.code == "success") {
		        layer.closeAll();
		        $scope.init();
		    }
		    else {
		        layer.closeAll();
		        layer.msg(data.message);
		    }
		}, function (data) {
		    layer.closeAll();
		    layer.msg("Error to confirm list.");
		});
    };

    $scope.selectAll = function () {
        $scope.model_select_all = !$scope.model_select_all;
        angular.forEach($scope.recipe_list, function (data, index, array) {
            data.selected = $scope.model_select_all;
        });
    };

    /*
     * Recipe Context Menu
     */
    $scope.menuOptionsList = [
            ['Edit', function ($itemScope) {
                $scope.showAddOrEditList($itemScope.item);
            }],
            ['Choose Recipe', function ($itemScope) {
                $scope.chooseRecipe($itemScope.item);
            }],
            null,
            ['Toggle Status', function ($itemScope) {
                $scope.toggleStatus($itemScope.item);
            }],
            null,
            ['Delete', function ($itemScope) {
                $scope.delete($itemScope.item);
            }]
    ];

    $scope.initRecipe = function () {
        $http.get(window.singleConfig.rootUrl + "api/admin/RecipeService/getShortInfo").then(function (result) {
            var list = result.data.data;
            var number = 1;
            angular.forEach(list, function (data, index, array) {
                data.index = number++;
                data.selected = false;
            });
            $scope.recipe_list = list;
        }, function () { });
    };

    $scope.initRecipe();
}]);